<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }" class="chat-card">
    <template #header>
      <div class="header">
        <el-row :gutter="20" align="middle">
          <el-col :span="12">
            <div class="room-title">
              <i class="el-icon-chat-dot-round" />
              <span>在线聊天室</span>
              <el-tag size="small" effect="dark" class="online-count">{{ onlineUsersCount }}人在线</el-tag>
            </div>
          </el-col>
          <el-col :span="12" class="text-right">
            <el-dropdown @command="handleCommand" trigger="click">
              <el-button type="primary" class="user-list-btn">
                <i class="el-icon-user" style="margin-right: 5px" />在线用户
              </el-button>
              <template #dropdown>
                <el-dropdown-menu class="user-dropdown">
                  <el-dropdown-item 
                    v-for="user in onlineUsers" 
                    :key="user" 
                    :command="user" 
                    divided 
                    :disabled="true"
                    :class="{ 'current-user': user === currentUser }">
                    <i class="el-icon-user" />
                    {{ user }}
                    <el-tag v-if="user === currentUser" size="small" type="success" class="self-tag">我</el-tag>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-col>
        </el-row>
      </div>
    </template>
    <el-row>
      <el-col :span="24">
        <!-- 消息区域 -->
        <el-scrollbar style="height: 300px;">
          <div ref="innerRef" class="message-container">
            <div v-for="(message, index) in messages" :key="index" :class="[
              'message-box',
              message.user === user ? 'message-right' : 'message-left',
              message.type === 'system' ? 'message-system' : ''
            ]">
              <div class="message-content">
                <div v-if="message.type !== 'system'" class="message-user">{{ message.user }}</div>
                <div class="message-text">{{ message.text }}</div>
              </div>
            </div>
          </div>
        </el-scrollbar>
      </el-col>
      <!-- 其他组件内容保持不变 -->
    </el-row>
    <template #footer>
      <div class="input-group">
        <el-input v-model="newMessage" placeholder="输入消息" @keyup.enter="sendMessage"></el-input>
        <el-button type="primary" @click="sendMessage">发送</el-button>
      </div>
    </template>
  </el-card>
</template>

<script setup>
import { ref, onMounted, nextTick, onBeforeUnmount } from 'vue';
import socket from '@/util/socket'; // 导入 socket 实例

const messages = ref([]); // 存储消息列表
const newMessage = ref(''); // 当前输入的消息
const user = ref(JSON.parse(localStorage.getItem("user_info")).username || 'Guest'); // 用户名
const onlineUsers = ref([]); // 在线用户列表
const onlineUsersCount = ref(0); // 在线用户数量
const currentUser = ref(user.value); // 当前用户

const chatScrollbar = ref(null);
const innerRef = ref(null);

// 发送消息方法
const sendMessage = () => {
  if (newMessage.value.trim()) {
    const message = {
      user: user.value,
      text: newMessage.value,
    };
    // 发送消息到服务器
    socket.emit('message', message);
    newMessage.value = '';
    scrollToBottom();
  }
};

// 滚动到底部的方法
const scrollToBottom = async () => {
  await nextTick(); // 等待 DOM 更新
  if (chatScrollbar.value) {
    chatScrollbar.value.setScrollTop(innerRef.value.scrollHeight);
  }
};

// 处理下拉菜单点击事件
const handleCommand = (command) => {
  // 可以根据需要处理点击事件
  console.log('点击了用户:', command);
};

// 监听来自服务器的消息
onMounted(() => {
  socket.on('message', (message) => {
    if (message.type === 'system') {
      messages.value.push(message);
      scrollToBottom();
    } else if (message.type === 'user') {
      messages.value.push(message);
      scrollToBottom();
    }
  });

  // 监听在线用户列表更新
  socket.on('onlineUsers', (users) => {
    onlineUsers.value = users;
    onlineUsersCount.value = users.length;
  });

  // 请求当前在线用户列表
  socket.emit('getOnlineUsers');
});

onBeforeUnmount(() => {
  socket.off('message');
  socket.off('onlineUsers');
});
</script>

<style scoped>
.chat-card {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.3s ease;
}

.room-title {
  font-size: 18px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.online-count {
  margin-left: 8px;
  font-weight: normal;
}

.text-right {
  text-align: right;
}

.user-list-btn {
  border-radius: 20px;
  padding: 8px 16px;
}

.user-dropdown {
  min-width: 200px;
}

.message-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-box {
  margin: 4px 0;
  opacity: 0;
  animation: fadeIn 0.3s ease forwards;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(10px); }
  to { opacity: 1; transform: translateY(0); }
}

.message-content {
  padding: 10px 16px;
  border-radius: 16px;
  display: inline-block;
  max-width: 70%;
  position: relative;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.2s ease;
}

.message-right {
  text-align: right;
}

.message-right .message-content {
  background: linear-gradient(135deg, #409eff, #36a3ff);
  color: white;
  border-bottom-right-radius: 4px;
}

.message-left .message-content {
  background: #f8f9fa;
  color: #333;
  border-bottom-left-radius: 4px;
}

.message-system {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 12px auto;
  max-width: 90%;
}

.message-system .message-content {
  background: linear-gradient(135deg, #e6a23c, #f0b14f);
  color: white;
  border-radius: 20px;
  padding: 8px 16px;
  font-size: 13px;
}

.message-user {
  font-size: 13px;
  color: #909399;
  margin-bottom: 4px;
  font-weight: 500;
}

.message-text {
  word-break: break-word;
  line-height: 1.4;
}

.el-scrollbar {
  background: #fff;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #ebeef5;
  transition: all 0.3s ease;
}

.input-group {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
  margin-top: 12px;
}

.el-input :deep(.el-input__inner) {
  border-radius: 20px;
  padding: 0 16px;
}

.el-button {
  border-radius: 20px;
  padding: 8px 20px;
  transition: all 0.2s ease;
}

.el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.current-user {
  background-color: #f0f9ff;
}

.self-tag {
  margin-left: 8px;
  border-radius: 12px;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .message-content {
    max-width: 85%;
  }
  
  .room-title {
    font-size: 16px;
  }
  
  .user-list-btn {
    padding: 6px 12px;
  }
}
</style>